package com.dodayum.controller;

import com.dodayum.MyJob;
import com.dodayum.entity.JobBean;
import com.dodayum.entity.JobInfo;
import com.dodayum.utils.JobUtils;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class Controller {

    @Resource
    private JobUtils jobUtils;

    @PostMapping("/add")
    public void add(@RequestParam Integer input) throws SchedulerException {
        String jobName = "job:\t" + input;
        String groupName = "group:\t" + input;
        JobBean jobBean = new JobBean();
        jobBean.setCron("0/1 * * * * ? ");
        jobBean.setJobGroup(groupName);
        jobBean.setJobName(jobName);
        jobBean.setJobClass(MyJob.class);
        Map<String, String> jobData = new HashMap<>();
        jobData.put("count", "1");
        jobBean.setData(jobData);
        System.out.println(jobUtils.createJob(jobBean));
    }

    @PostMapping("/stop")
    public void stop(@RequestParam Integer input) throws SchedulerException {
        System.out.println(input);
        String jobName = "job:\t" + input;
        String groupName = "group:\t" + input;
        JobBean jobBean = new JobBean();
        jobBean.setJobName(jobName);
        jobBean.setJobGroup(groupName);
        jobUtils.pauseJob(jobBean);
    }

    @PostMapping("/run")
    public void run(@RequestParam Integer input) throws SchedulerException {
        System.out.println(input);
        String jobName = "job:\t" + input;
        String groupName = "group:\t" + input;
        JobBean jobBean = new JobBean();
        jobBean.setJobName(jobName);
        jobBean.setJobGroup(groupName);
        jobUtils.resumeJob(jobBean);
    }

    @PostMapping("/remove")
    public void remove(@RequestParam Integer input) throws SchedulerException {
        System.out.println(input);
        String jobName = "job:\t" + input;
        String groupName = "group:\t" + input;
        JobBean jobBean = new JobBean();
        jobBean.setJobName(jobName);
        jobBean.setJobGroup(groupName);
        System.out.println(jobUtils.deleteJob(jobBean));
    }

    @PostMapping("/update")
    public void update(@RequestParam Integer input) {
        System.out.println(input);
//        String jobName = "job:\t" + input;
//        String groupName = "group:\t" + input;
    }

    @PostMapping("/getAll")
    public List<JobInfo> getAll() throws SchedulerException {
        return jobUtils.queryAll();
    }

}
